import settings from "../settings";
import { getAuthen } from "@/utils/getAuthen";
import moment from "moment";
import storage from "@/utils/storageTool";
import { getEnterpriseId } from "@/utils/getEnterpriseId";

const noncestr = Math.random()
  .toString(36)
  .substring(2);
const timestamp = +moment.utc();

// 带Origin后缀的通过getter获取
export const state = () => ({
  openIdOrigin: storage.getItem("openId") || "olry95_yBm1_5lJ66LrS5XdyXUb4",
  accessTokenOrigin: storage.getItem("accessToken") || "bd9cbd169a568bd0d21e4517834f3261",
  unionIdOrigin: storage.getItem("unionId") || "",
  userInfo:
    {
      balance: 0,
      blogNickName: "LayX",
      blogOpenid: "olry95_yBm1_5lJ66LrS5XdyXUb4",
      couponCount: 0,
      enterpriseName: "望都县萌拓加油站",
      followStatus: "1",
      gradeCode: "1",
      gradeName: "普卡",
      growUpValue: 0,
      gzhAppId: "wx3d36094f71a1ceda",
      integral: 0,
      memberCode: "23070742613",
      missValue: 900000000,
      mobilePhone: "13713504691",
      numberOfEntry: 0,
      originId: "gh_42a6fb6bbc6c",
      registeDate: "2023-07-07 00:31:04",
      stationId: 136,
      userId: 520343,
    },
  enterpriseIdOrigin: getEnterpriseId(),
  appIdOrigin: storage.getItem("appId") || "wx3d36094f71a1ceda",
  phoneOrigin: storage.getItem("phone") || "13713504691",
  noncestr,
  timestamp,
  signature: "",
  enterpriseInfo:
    JSON.parse(
      !!storage.getItem("enterpriseInfo")
        ? storage.getItem("enterpriseInfo")
        : "{}"
    ) || {}, // 这个暂时没有使用到
  consumerIdOrigin: storage.getItem("consumerId") || "",
  payPasswordInfoOrigin: JSON.parse(
    !!storage.getItem("payPasswordInfo")
      ? storage.getItem("payPasswordInfo")
      : "{}"
  )
});

export const getters = {
  openId: state => {
    if (!state.openIdOrigin) {
      // getAuthen()       // 手机号做标识 openid 不再作为拉起认证的入口
    }
    return state.openIdOrigin;
  },
  accessToken: state => {
    if (!state.accessTokenOrigin) {
      console.log("------accessTokenOrigin-----");
      getAuthen();
    }
    return state.accessToken;
  },
  enterpriseId: state => {
    if (!state.enterpriseIdOrigin) {
      // getAuthen()
      alert("请通过站点网址访问~" + state.enterpriseIdOrigin);
    }
    return state.enterpriseIdOrigin;
  },
  appId: state => {
    if (!state.appIdOrigin) {
      console.log("------appIdOrigin-----");
      getAuthen();
    }
    return state.appIdOrigin;
  },
  unionId: state => {
    if (!state.unionIdOrigin) {
      // getAuthen()
    }
    return state.unionIdOrigin;
  },
  phone: state => {
    if (!state.phoneOrigin) {
      console.log("------phoneOrigin-----");
      getAuthen();
    }
    return state.phoneOrigin;
  },
  userInfo: state => state.userInfo,

  // 消费者id（也是当前登录者id)
  consumerId: state => {
    return state.consumerIdOrigin;
  },
  // 支付信息
  payPasswordInfo: state => {
    return state.payPasswordInfoOrigin;
  }
};

export const mutations = {
  setOpenId(state, openId) {
    if (!openId) {
      openId = "";
    }
    storage.setItem("openId", openId);
    state.openIdOrigin = openId;
  },
  setPhone: (state, phone) => {
    if (!phone) {
      phone = "";
    }
    storage.setItem("phone", phone);
    state.phoneOrigin = phone;
  },
  setAccessToken(state, accessToken) {
    storage.setItem("accessToken", accessToken);
    state.accessTokenOrigin = accessToken;
  },
  setUnionId(state, unionId) {
    if (!unionId) {
      unionId = "";
    }
    storage.setItem("unionId", unionId);
    state.unionIdOrigin = unionId;
  },
  setUserInfo(state, userInfo) {
    storage.setItem("userInfo", JSON.stringify(userInfo));
    state.userInfo = userInfo;
  },
  setSignature(state, signature) {
    state.signature = signature;
  },
  setEnterpriseId(state, enterpriseId) {
    state.enterpriseIdOrigin = enterpriseId;
  },
  setAppId(state, appId) {
    storage.setItem("appId", appId);
    state.appIdOrigin = appId;
  },

  // 更新保存油企信息
  setEnterpriseInfo(state, enterpriseInfo) {
    storage.setItem("enterpriseInfo", JSON.stringify(enterpriseInfo));
    state.enterpriseInfo = enterpriseInfo;
  },

  // 更新 新用户走闪付阶段保存的用户信息
  setUserInfoSF(state, userInfoSF) {
    storage.setItem("userInfoSF", JSON.stringify(userInfoSF));
    state.userInfoSF = userInfoSF;
  },

  // 消费者的用户id
  setConsumerId(state, consumerId) {
    storage.setItem("consumerId", consumerId);
    state.consumerIdOrigin = consumerId;
  },
  setPayPasswordInfo(state, obj) {
    console.log("更新了支付密码信息吗");
    storage.setItem("payPasswordInfo", JSON.stringify(obj));
    state.payPasswordInfoOrigin = obj;
  }
};

export const actions = {
  // async login({ commit, state, getters }, query) {

  //   const gzhAuthenRes = await this.$axios.$post("/selectCardMobilePhone", query)
  //   if (gzhAuthenRes.retCode !== 0) { return Promise.reject("拉取手机号失败") }
  //   console.log('拉取成功', gzhAuthenRes)
  //   const openId = query.openid;
  //   const phone = gzhAuthenRes.data.phone;
  //   const unionId = gzhAuthenRes.data.unionid;
  //   commit("setOpenId", openId)
  //   commit ("setPhone", phone)
  //   commit ("setUnionId", unionId)

  //   // commit("setUnionId", unionId)
  //   // const getUserInfoRes = await this.$axios.$get("/getGzhUserInfo", {
  //   //   params: {
  //   //     openId: openId,
  //   //     enterpriseId: getters.enterpriseId
  //   //   }
  //   // })
  //   // if (getUserInfoRes.retCode !== 0) { return Promise.reject("拉取用户信息失败") }
  //   // commit("setUserInfo", getUserInfoRes.data)
  //   // const saveUserInfoRes = await this.$axios.$post("/addAppUserInfo", {
  //   //   appType: "1",
  //   //   openId: openId,
  //   //   unionId: unionId,
  //   //   enterpriseId: getters.enterpriseId, //油站Id
  //   //   blogNickName: getUserInfoRes.data.nickname,
  //   //   sexFlag: getUserInfoRes.data.sex,
  //   //   blogProfilePhoto: getUserInfoRes.data.headimgurl
  //   // })
  //   // if (saveUserInfoRes.retCode !== 0) { return Promise.reject("存取用户信息失败") }
  //   return Promise.resolve("用户登录成功")
  // },
  // async loginGetOpenId({ commit, state, getters }, code) {
  //   const gzhAuthenRes = await this.$axios.$get("/getGzhAuthorizeInfo", {
  //     params: {
  //       code,
  //       enterpriseId: getters.enterpriseId,
  //     },
  //   })
  //   if (gzhAuthenRes.retCode !== 0) { return Promise.reject("拉取openId失败") }
  //   console.log('拉取成功', gzhAuthenRes)
  //   const openId = gzhAuthenRes.data.openid;
  //   console.log('openId', openId)
  //   // const accessToken = gzhAuthenRes.data.access_token;
  //   // const unionId = gzhAuthenRes.data.unionid;
  //   commit("setOpenId", openId)
  //   // commit("setAccessToken", accessToken)
  //   // commit("setUnionId", unionId)
  //   // const getUserInfoRes = await this.$axios.$get("/getGzhUserInfo", {
  //   //   params: {
  //   //     openId: openId,
  //   //     enterpriseId: getters.enterpriseId
  //   //   }
  //   // })
  //   // if (getUserInfoRes.retCode !== 0) { return Promise.reject("拉取用户信息失败") }
  //   // commit("setUserInfo", getUserInfoRes.data)
  //   // const saveUserInfoRes = await this.$axios.$post("/addAppUserInfo", {
  //   //   appType: "1",
  //   //   openId: openId,
  //   //   unionId: unionId,
  //   //   enterpriseId: getters.enterpriseId, //油站Id
  //   //   blogNickName: getUserInfoRes.data.nickname,
  //   //   sexFlag: getUserInfoRes.data.sex,
  //   //   blogProfilePhoto: getUserInfoRes.data.headimgurl
  //   // })
  //   // if (saveUserInfoRes.retCode !== 0) { return Promise.reject("存取用户信息失败") }
  //   return Promise.resolve("用户获取openid成功")
  // },
  async getSdkConfig({ commit, state, getters }, config) {
    const sdkSignRes = await this.$axios.$get("/getSignature", {
      params: {
        noncestr: state.noncestr,
        timestamp: state.timestamp,
        url: window.location.href.replace(/#(\w|\W){0,}/g, ""),
        enterpriseId: getters.enterpriseId
        // enterpriseId:7
      }
    });
    if (sdkSignRes.retCode !== 0) {
      Promise.reject("获取Sdk签名错误");
    }

    commit("setSignature", sdkSignRes.data);

    return Promise.resolve({
      debug: settings.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: getters.appId, // 必填，公众号的唯一标识
      // appId:'wxc8189d3b3a7283e0',
      timestamp: state.timestamp, // 必填，生成签名的时间戳
      nonceStr: state.noncestr, // 必填，生成签名的随机串
      signature: sdkSignRes.data,
      jsApiList: config.jsApiList, // 必填，需要使用的JS接口列表
      openTagList: config.openTagList // 跳转小程序时必填
    });
  },

  async getSdkConfig2({ commit, state, getters }, config) {
    const sdkSignRes = await this.$axios.$get("/getSignature", {
      params: {
        noncestr: state.noncestr,
        timestamp: state.timestamp,
        url: window.location.href.split("#")[0],
        enterpriseId: getters.enterpriseId
      }
    });
    if (sdkSignRes.retCode !== 0) {
      Promise.reject("获取Sdk签名错误");
    }

    commit("setSignature", sdkSignRes.data);

    return Promise.resolve({
      debug: settings.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: getters.appId, // 必填，公众号的唯一标识
      timestamp: state.timestamp, // 必填，生成签名的时间戳
      nonceStr: state.noncestr, // 必填，生成签名的随机串
      signature: sdkSignRes.data,
      jsApiList: config.jsApiList, // 必填，需要使用的JS接口列表
      openTagList: config.openTagList // 跳转小程序时必填
    });
  },

  async getAppId({ commit, state, getters }, enterpriseId) {
    console.log("先获取Appid");
    const appIdRes = await this.$axios.$get("/getStationGzhAppId", {
      params: {
        enterpriseId: enterpriseId
      }
    });
    console.log("getStationGzhAppId----appIdRes", appIdRes);
    console.log("getStationGzhAppId----appIdRes", appIdRes.data.appId);
    if (appIdRes.retCode !== 0) {
      return Promise.reject("获取appid失败");
    }
    commit("setEnterpriseId", enterpriseId);
    commit("setAppId", appIdRes.data.appId);
    return Promise.resolve({
      enterpriseId,
      appId: appIdRes.data.appId
    });
  }
};
